package com.youku.ast;

import java.util.LinkedList;
import java.util.List;

import com.youku.compiler.TokenType;

/**
 * if语句
 * 
 * @author loda
 *
 */
public class IfStatementAst extends Ast {

	public IfStatementAst(Ast... asts) {
		super(asts);
	}

	/**
	 * if语句
	 * 
	 * @return
	 */
	public Ast ifStatement() {
		return getChild(0);
	}

	/**
	 * elsif语句
	 * 
	 * @return
	 */
	public List<Ast> elsifStatement() {
		List<Ast> elsifStats = new LinkedList<>();
		for (Ast ast : children()) {
			if (ast.getTokenType() == TokenType.ELSIF) {
				elsifStats.add(ast);
			}
		}

		return elsifStats;
	}

	/**
	 * else执行语句
	 * 
	 * @return
	 */
	public Ast elseStatement() {
		Ast lastChild = getLastChild();
		if (lastChild.getTokenType() == TokenType.ELSE) {
			return lastChild;
		} else {
			return null;
		}
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();

		for (Ast ast : elsifStatement()) {
			builder.append("elsif" + ast);
		}
		Ast ast = elseStatement();
		if (ast != null)
			builder.append("else" + ast);

		return "if " + ifStatement() + builder.toString();
	}

}
